import subprocess

from utils import close_qemu, read_config
from get_ip import get_eth0_ip
import sys


def run_robot_test(host_ip, user_name, password, ports, test_suite):
    """执行Robot Framework测试"""
    # 构造变量参数
    variables = [
        f"OPENUBMC_HOST:{host_ip}",
        f"OPENUBMC_USERNAME:{user_name}",
        f"OPENUBMC_PASSWORD:{password}",
        f"IPMI_PORT:{ports['ipmi']}",
        f"SSH_PORT:{ports['ssh']}",
        f"HTTP_PORT:{ports['https']}"
    ]

    # 构造robot命令
    cmd = ["robot"]
    for var in variables:
        cmd.extend(["-v", var])
    cmd.extend(test_suite)

    print("执行命令:", " ".join(cmd))
    process = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )

    # 实时打印输出
    for line in process.stdout:
        print(line, end="")
    
    process.wait()
    return process.returncode

def get_log():
    grep_cmd = ["grep", "-F", 'window.output["strings"] = window.output["strings"].concat', "log.html"]
    result = subprocess.run(grep_cmd, capture_output=True, text=True)
    print(result.stdout)  # 打印 grep 的输出

def testing(host_ip, option=True):
    """主测试流程"""

    # 读取配置文件---端口信息
    config = read_config()
    ports = config['mapports']
    ip=host_ip
    openubmc_username = "Administrator"
    openubmc_password = "Admin@90000"

    # 运行的测试套件
    if option:
        test_suite = [
            "-A", "test_lists/QEMU_CI",
            "test_cases/1_cli",
            "test_cases/2_web",
            "test_cases/3_redfish",
            "test_cases/4_ipmi"
        ]
    else:
        test_suite = ["test_cases/"]

    print("执行 Robot Framework 测试...")
    ret = run_robot_test(
        host_ip=ip,
        user_name=openubmc_username,
        password=openubmc_password,
        ports=ports,
        test_suite=test_suite
    )

    if ret != 0:
        print("❌ 测试失败")
        get_log()
        close_qemu()
        exit(1)
    print("✅ 测试成功")
    close_qemu()

if __name__ == "__main__":
    # 支持传入参数 --HOST_IP
    host_ip = "127.0.0.1"
    for i, arg in enumerate(sys.argv):
        if arg == "--HOST_IP" and i + 1 < len(sys.argv):
            host_ip = sys.argv[i + 1]
    testing(host_ip)
